/**办理入院JS
 */


// 办理入院

var indexBanRy;
function handleAdmission() {
	$("#handle_admission").on("click",function() {
				var that = this;
				$(that).attr("disabled",true);
				// var vaa01=$("#vaa01").val();
				var isoperate = isOperateAdvice();
				if(!isoperate){
					layer.msg("该病人已经过了开嘱期限，请重新挂号！",{ time: 3000,icon: 0,skin: 'layui-layer-msg0'});
					$(that).removeAttr("disabled");
					return false;
				}
				if (isOwnchose) {
					var url1 = rootUrl + "/treatment/handleAdmission";
					var params1 = {};
					var url2 = rootUrl + "/treatment/queryAbj1";
					var params = {
							vaa01:$("#vaa01").val()
					}
					var params2 = {};
					params2.params = JSON.stringify(params);
					
					var url3 = rootUrl + "/clidoctor/selectDataByScriptId";
					var param3 =
					{
							paramStr :JSON.stringify(params),
							ID:10000009
					}
					$.when($.get(url1, params1),$.get(url2, params2),$.get(url3, param3)).done(function(data,data1,data2) {
						debugger;
						var deptinof = data[0].list;
						var payinof = data1[0].list;
						var paydefaut = data1[0].rows;
						//过敏药物
						var druginfo = data2[0].list;
						var list = {}
						list.deptinof  = deptinof ;
						list.payinof   = payinof ;
						list.druginfo   = druginfo ;
						laytplUrl(myurl + "/module/banliruyuan.html", list,function(data, html) {
							indexBanRy = layer.open({
										type : 1,
										// scrollbar : false,
										title : "办理入院",
										area : [ "80%", "80%" ],
										shade : 0.1,
										maxmin : true,
										content : html,
										closeBtn : 1,
										success : function() {
											$("select").select2({
												language: "zh-CN"
											});
											initDiagnoseByParam($("#diagnose_tip"));
											//加载过敏药物
											AllergyDrugEvent();
											if(paydefaut.length> 0 ){
												var paydefautid = data1[0].rows[0].abj01;
												$("#payinfo_id").val(paydefautid).trigger("change")
											}
											
											$(that).removeAttr("disabled");
											deleteTr();
											inhospitalDiagnose();//加载病人诊断
											diagonoseInHospital();//诊断下拉框
											tabChangeEvent();
//											xySelectDiv();
											var date = new Date();
											var vbn11 = new Date();
											vbn11.setDate(date.getDate() + 3);
											vbn11 = vbn11.Format("yyyy-MM-dd hh:mm:ss");
											var vbn10 = date.Format("yyyy-MM-dd hh:mm:ss");
											var vbn04 = date.Format("yyyy-MM-dd hh:mm:ss");
											$("#vbn10").val(vbn10);
											$("#vbn11").val(vbn11);
											$("#vbn04").val(vbn04);
											var url1 = rootUrl + "/cliparamter/clihomepagepatientbasicinfo";
									 		var para1 =
									 		{
									 			VAA07 : $("#vac01").val()
									 		};
									 		$.ajax({
									 			url:url1,
									 			type:"post",
									 			dataType:"json",
									 			data:para1,
									 			assync:false,
									 			success:function(data)
									 			{
									 	 			if (data && data.list && data.list.length > 0)
									 	 			{
									 	 				var temp1 = data.list[0];
//									 	 				vbn1.vbn07 = temp1.vac21;//联系人
//									 	 		    	vbn1.vbn08 = temp1.vac24;//联系电话
									 	 			}
									 			}
									 		})
									 		//tagsinputDiagnoseSearch_inhospital(); 
											$("#remove_action").on("click",function() {
												layer.close(indexBanRy);
											})
											$.ajax({
												url:rootUrl+"/treatment/queryVbn1ByVac01",
												type:"get",
												dataType:"json",
												data:{vac01:$("#vac01").val()},
												async:false,
												success:function(data)
												{
													if (datas && data.list && data.list.length>0)
													{
														//提取库里面的入院信息
														var temp = data.list[0];
														$("#ruyuankeshi").val(temp.bck01);
														$("#vbn09").val(temp.vbn09);
														$("#vbn10").val(temp.vbn10);
														$("#vbn11").val(temp.vbn11);
														$("#vbn14").val(temp.vbn14);
														$("#vbn04").val(temp.vbn04);
														if(temp.vbn20){
															var vbn20arr = temp.vbn20.split(",");
															for(var i = 0; i<vbn20arr.length; i++){
																$("#vbn20").find("input[value="+vbn20arr[i]+"]").prop("checked",'true')
															}
														}
														if(temp.vbn21){
															var vbn21arr = temp.vbn21.split(",");
															for(var k = 0; k<vbn21arr.length; k++){
																$("#vbn21").find("input[value="+vbn21arr[k]+"]").prop("checked",'true')
															}
														}
														var url1 = rootUrl + "/cliparamter/clihomepagepatientbasicinfo";
												 		var para1 =
												 		{
												 			VAA07 : $("#vac01").val()
												 		};
												 		$.ajax({
												 			url:url1,
												 			type:"post",
												 			dataType:"json",
												 			data:para1,
												 			assync:false,
												 			success:function(data)
												 			{
												 	 			if (data && data.list && data.list.length > 0)
												 	 			{
												 	 				var temp1 = data.list;
												 	 				$("#vbn07").val(temp.vbn07?temp.vbn07:temp1.vac21);//联系人
												 	 				$("#vbn08").val(temp.vbn08?temp.vbn08:temp1.vac24);//联系电话
												 	 			}
												 			}
												 		});
														/*$.ajax({
															url:"",
															type:"get",
															dataType:"",
															data:{vac01:$("#vac01").val()},
															success:function(json)
															{
																
															}
														});
														$("#ruyuan_select").tagsinput('add', temp.vao15, temp.bak01);*/
												 	
													}
												}
											});
										},
										min: function (layero) {
							                var times = layero.attr('times');
							                $('#layui-layer-shade' + times).hide();
							            },
							            restore: function (layero) {
							                var times = layero.attr('times');
							                if ($('#layui-layer-shade' + times).css('display') == 'none') {
							                    $('#layui-layer-shade' + times).show();
							                }
							            },
									});
								});
					});
				} else {
					layer.msg("请选择病人", {
						time : 2000,
						icon : 0,
						skin: 'layui-layer-msg0'
					});
					$(that).removeAttr("disabled");
				}

			})
}
//回显过敏药物
function showAllergyDrug(){
	var param =
	{
		vaa01 : $("#vaa01").val()
	}
	$.get(rootUrl + "/clidoctor/selectDataByScriptId",{ID:10000009,paramStr: JSON.stringify(param)}, function(json){
		debugger
		if(json){
		}
	
	}) 

}
//加载诊断
function inhospitalDiagnose(){
	var vac01 = $("#vac01").val();
	params = {};
	params.vac01 = vac01;
	//获取病人诊断的信息
	$.ajax(
		{
		data : params,
		url : rootUrl + "/treatment/getZhenduanShouye",
		type : 'get',
		dataType : 'json',
		success : function(data)
		{
			debugger;
			for(var i=0;i< data.list.length;i++){
				$("#diagnose_tip").tagsinput('add', data.list[i].vao15, data.list[i].vao01);
			}
		}
	})
}



//加载病人信息
function tabChangeEvent(){
	$("#hospital_tab li").on("click",function(){
		if($(this).find("a").attr("href") == "#patient_info_t"){ //加载病人信息
			if($("#edit_patient_form_info").length<1){
				if($.inArray("brxx_mz",authorityArr) >=0){
					deitPatinetInfo("RY"); //办理入院加载病人信息标志
				}
			}
		}
		
	})
}
/*
 * 保存入院信息
 */
function saveRuyuan()
{
	saveEditPatientInfo();//保存病人信息
	saveAllergyDrug();//保过敏药物断信息
	debugger;
	//校验
	//获取数据
//	var n = /^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$/; //非负数
	var n = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/; //非负数
//	 var flag = $("#isPrintRuyuan").parent().attr("class").indexOf("checked");
	var flag=$("#isPrintRuyuan").is(':checked');
	var ruyuankeshi = $("#ruyuankeshi").find("option:selected").val();
	var vbn09 = $("#vbn09").val();
	
	if(!n.test(vbn09)){
		$('#hospital_tab a[href="#hospital_info_t"]').tab('show');
		layer.tips("请填写正确的预交金金额！", $("#vbn09"));
//		layer.alert("请填写正确的预交金金额！",{icon:0})
		return false;
	}
	var vbn10 = $("#vbn10").val();
	var vbn11 = $("#vbn11").val();
	var vbn14 = $("#vbn14").val();
	var vbn04 = $("#vbn04").val();

	//新增或者修改数据
	 var url = rootUrl + "/treatment/saveRuyuan";
	 var params = {};
	 var vbn1 = {};
	 //入院信息
	 vbn1.bce01 = bce01;
	 vbn1.bce03 = bce03;
	 vbn1.bck01b = $("#bck01b").val();
	 vbn1.vac01 = $("#vac01").val();
	 vbn1.vaa01 = $("#vaa01").val();
	 vbn1.bck01 = ruyuankeshi;
	 vbn1.vbn09 = vbn09;
	 vbn1.vbn10 = vbn10;
	 vbn1.vbn11 = vbn11;
	 vbn1.vbn14 = vbn14;
	 vbn1.vbn04 = vbn04;
	 vbn1.vbn07 = $("#vbn07").val();//联系人
     vbn1.vbn08 = $("#vbn08").val();//联系电话
    //病情
     var vbn20str = "";
     $("#vbn20").find("input:checked").each(function(index,item){
    	 if(index == 0){
    		 vbn20str += $(item).val();
    	 }else{
    		 
    		 vbn20str += ","+$(item).val();
    	 }
     })
     //接送方式
     var vbn21str = "";
     $("#vbn21").find("input:checked").each(function(index,item){
    	 if(index == 0){
    		 vbn21str += $(item).val();
    	 }else{
    		 
    		 vbn21str += ","+$(item).val();
    	 }
     })
     
     
     vbn1.vbn20 = vbn20str;//病情
     vbn1.vbn21 = vbn21str;//接送方式
     var vaa1={};
     vaa1.abj01 = $("#payinfo_id").val();//付款类型
     vaa1.vaa01 = $("#vaa01").val();
	 //诊断信息
	 var vao1Arr = [];
	 var temp = $(".bootstrap-tagsinput").children("span");
	 for(var i=0;i<temp.length;i++)
	 {
		 var cam01 = $(temp[i]).attr("id");
		 var vao15 = $(temp[i]).text();
		 var vao1 = {};
		 vao1.vac01 = $("#vac01").val();
		 vao1.vaa01 = $("#vaa01").val();
		 vao1.vao01 = cam01;
    	 vao1.vao07 = "0";
    	 vao1.vaf01 = "0";
    	 vao1.vao11 = "1";
    	 vao1.cam01 = cam01;
    	 vao1.vao15 = vao15;
    	 vao1.bak01a = "0";
    	 vao1.vao18 = "0";
    	 vao1.vao22 = "0";
    	 vao1.fsign = "1";
    	 vao1.bgp01 = "";
    	 vao1.ady01 = "";
    	 vao1Arr.push(vao1);
	 }
	 params.vbn1 = JSON.stringify(vbn1);
	 params.vao1 = JSON.stringify(vao1Arr);
	 params.vac01 = $("#vac01").val();
	 params.vaa1 = JSON.stringify(vaa1);;
	 $.get(url,params,function(data){
		 if(data)
		 {
			 if(data.result=="Success")
			 {
				 layer.msg("办理入院成功！", {time:2000,icon:1,skin: 'layui-layer-msg1'});
				 if(valueArr['p_100_105002_409']==1){
					 layer.closeAll();
				 }
//				 parent.layer.close(parent.layer.getFrameIndex(window.name));//关闭弹出层
				
				 if(flag)
				 {
					 print2(110,$("#vac01").val());
				 }
			 }
			 else 
			 {
				 layer.msg(data.resultMsg, {time:2000,icon:2,skin: 'layui-layer-msg2'});
			 }
		 }
		 else
		 {
			 layer.msg("数据异常，请联系管理员", {time:2000,icon:2,skin: 'layui-layer-msg2'});
		 }
	 });
	  
}
//办理入院加载打印格式
function inhospitalPrintType(){
	debugger;
	var url = printUrl + "/printtemprest/findListByRid/2" + "?jsessionids=" + $.cookie('jsessionids');
	var para ={};
	$.ajax(
	{
	url : url,
	type : "get",
//	async : false,
	dataType : "json",
	traditional : true,
	success : function(data)
	{
		var defaultV2;
		if (data)
		{
			var html = "";
			for (var i = 0; i < data.length; i++)
			{
				html += '<option  value=' + data[i].id +' >' + data[i]['name'] + '</option>';
				if (data[i]['xdefault'] == "1")
				{
					defaultV2 = data[i].id;
				}
			}
			$("#inhospital_print_type").empty().append(html);
			$("#inhospital_print_type").select2();
			if (defaultV2)
			{
				$("#inhospital_print_type").val(defaultV2).trigger("change");
			}
		}
	}
	})
}

//直接打印
function inhospitalPrint()
{
	debugger;
	var id = $("#inhospital_print_type").val();
	print2(id,$("#vac01").val());
}

//入院通知单打印预览
function print2(id,vac01)
{
	var url = printUrl+"/printtoolrest/printToPdf/"+id+"?vac01="+vac01;
	layer.closeAll();         // 打印前先关闭已经打开 layer 弹框
    layer.open({
        type: 2,
        title:false,          // title 不显示
        closeBtn: 0,          // 不显示  layer 弹框关闭按钮
        shadeClose: false,
        shade: false,
        area: ['0%', '0%'],   //在页面上不显示
        content: url,         //iframe的url,
        success:function(){
            // $("#cover").addClass("hidden");  //去掉遮罩层
            console.log($("#icon"));
        }
    });
}

//直接打印
function inhospitalPrintView(){
	var id = $("#inhospital_print_type").val();
	var vac01 = $("#vac01").val();
	var url = printUrl+"/printtoolrest/printToPdfView/"+id+"?vac01="+vac01+"&jsessionids="+$.cookie('jsessionids');
	window.open(url);
}

/*---------------------------------------------------------办理入院的过敏药物----------------------------------------------------------------*/

function AllergyDrugEvent(){
	addAllergyDrugTr();
	delAllergyDrugTr();
	AllergyDrugItem();
}
//新增tr
function addAllergyDrugTr(flag){
	 var trHtml = '<tr>';
	 trHtml += '<td><input type="text" value="" class="form-input search_allergy" placeholder="这是过敏药物标签" /><input type="hidden" class = "bbx01" value=""/></td>';
	 trHtml += '<td><input class="shouye_shuoming form-input" type="text" value=""></td>';
	 trHtml +='<td><input class="btn btn-white btn-min-xs del_allergy del_allergy_js" type="button" value="删除 " />';
	 trHtml +='<input class="btn btn-white btn-min-xs add_allergy" type="button" value="新增 " /></td>;'
	 trHtml +='</tr>';
	if(flag == -1){
		$("#allergy_drug_table tbody").append(trHtml);
		AllergyDrugEvent(); //加载完后注册事件
	}else{
		$("#diagnose_info_t .add_allergy").off("click").on("click",function(){
			$(this).parents("tr").before(trHtml);
			$(this).parents("tr").prev().find(".search_allergy").focus();
			AllergyDrugEvent(); //加载完后注册事件
		})
	}
}
//删除tr
function delAllergyDrugTr(){
	$("#diagnose_info_t .del_allergy").on("click",function(){
		 $(this).parents("tr").remove();
		 if($("#allergy_drug_table tbody tr").length<1){
			 addAllergyDrugTr(-1);
		 }
	})
}

//点击下拉搜索过敏药物
function AllergyDrugItem(){ 

	$("#diagnose_info_t .search_allergy").on("click input", function(){
		event.stopPropagation(); 
		if ($("#drop_box_id").length<1 ||$("#drop_box_id").is(":hidden"))
		{
			var curinput = $(this);
			var text = $(this).val();
			var thisTop = $(this).position().top + $(this).outerHeight();
			thisLeft = $(this).position().left;
			$("#allergy_dropbox").simpleDrop(
			{
				menus :[{
				css :{
					left : thisLeft,
					top : thisTop + "px",
					transform : "none",
					display : "block"
					},
				ids :{
					dropid : "drop_box_allergy",
					inputid : "drop_input_id",
					sbtnid : "drop_sbtn_id",
					tableid : "drop_table_id",
					},
				which : "tpl2.html",
				event : function(ids)
				{
					$("#"+ids.inputid).val(text);
					ids.curinput = curinput;
					allergyOperation(ids);
				}
				}]
			})
		}
	})
	
}
function allergyOperation(ids){
	$("#"+ids.inputid).keydown(function (e) {
	      if (e.which === 13) {
	    	  searchAllergyTable(ids);
	      }
	      });
		$("#"+ids.sbtnid).on("click",function(){
			debugger;
			 searchAllergyTable(ids);
		})
}

//查询表格事件
function searchAllergyTable(ids)
{
	var lTxt = $("#" + ids.inputid).val();
	if (!!lTxt)
	{
		var param =
		{
			lTxt : "%" + lTxt + "%"
		}
		$.get(rootUrl + "/clidoctor/selectDataByScriptId",{ID : 10000008,paramStr : JSON.stringify(param)}, function(json)
		{
			debugger
			if (json)
			{
				var list = json.list;
				$("#" + ids.tableid).GridUnload();
				jQuery("#" + ids.tableid).jqGrid(
				{
				data : list,
				datatype : "local",
				height : 'auto',
				width : 'auto',
				autowidth : true,
				autoheight : true,
				rownumbers:true,
				rowNum:-1,
				colModel :
				[
					{label : "编码",name : 'bbx04',align : "left"},
					{label : "药品名称",name : 'bbx05',align : "left"},
					{name : 'bbx01',hidden : true,},
					{name : 'abbrp',hidden : true,}
				],
				
				ondblClickRow : function(rowid, status)
				{
					//添加数据
					ids.rowid = rowid;
					setDataToInput(ids);
				},
				onSelectRow : function(rowid, status)
				{

				},
				loadComplete : function(data)
				{
					$("#" + ids.tableid).jqGrid("setSelection", 1);
				}
				});
			}

		})
	}
	else
	{
		layer.tips("请输入检索条件", $("#" + ids.inputid));
	}
}
//添加数据
function setDataToInput(ids){
	var row = $("#" + ids.tableid).jqGrid("getRowData", ids.rowid);
	$(ids.curinput).val(row.bbx05);
	$(ids.curinput).next().val(row.bbx01);
	$("#" + ids.dropid).hide();
	//新增一行
	$(ids.curinput).parents("tr").find(".add_allergy").trigger("click")
}
//保存过敏药物数据
function saveAllergyDrug(){
	debugger;
	var val1List=[];
	var vaa01_a = $("#vaa01").val();
	$("#allergy_drug_table tbody tr").each(function(i,e){
		var bbx05 = $(e).find(".search_allergy").val();
		if(bbx05){
			var bbx01 = $(e).find(".bbx01").val();
			var val05 = $(e).find(".shouye_shuoming").val();
			var obj = {};
			obj.vaa01 = vaa01_a;
			obj.bbx01 = bbx01;
			obj.bbx05 = bbx05;
			obj.val05 = val05;
			val1List.push(obj);
		}
	})
	var url = rootUrl + "/cliparamter/saveVal1";
	var params = {
			val1List:val1List,
			vaa01:vaa01_a
	}
	var para = {
		params:JSON.stringify(params)
	}
	$.when($.post(url, para)).done(function(data) {
		if(data.result == "Success"){
			layer.msg("过敏药物保存成功！", {
				time : 2000,
				icon : 1,
				skin: 'layui-layer-msg1'
			});
		}
	})
}

/*---------------------------------------------------------办理入院的过敏药物--end--------------------------------------------------------------*/


